package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.enums.ResultCode;
import com.example.forum.common.enums.UserStatus;
import com.example.forum.common.utils.MD5Util;
import com.example.forum.common.utils.UUIDUtil;
import com.example.forum.config.AppConfig;
import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * @author hanzishuai
 * @date 2025/3/22 18:10
 * @Description 用户接口
 */
@Tag(name = "用户接口")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    /**
     * Created by hanzishuai on 2025/3/22
     *
     * @param username       用户名
     * @param nickname       昵称
     * @param password       密码
     * @param passwordRepeat 确认密码
     * @return com.example.forum.common.AppResult
     * @Description 用户注册
     */
    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public AppResult register(@Parameter(description = "用户名") @RequestParam("username") @NonNull String username,
                              @Parameter(description = "昵称") @RequestParam("nickname") @NonNull String nickname,
                              @Parameter(description = "密码") @RequestParam("password") @NonNull String password,
                              @Parameter(description = "确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {


        if (!password.equals(passwordRepeat)) {
            log.info(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);

        // 加密密码
        String salt = UUIDUtil.UUID_32();
        String encryptPassword = MD5Util.md5Salt(password, salt);

        user.setSalt(salt);
        user.setPassword(encryptPassword);

        userService.createNormalUser(user);

        return AppResult.success();
    }


    /**
     * Created by hanzishuai on 2025/4/8
     *
     * @param username
     * @param password
     * @return com.example.forum.common.AppResult
     * @Description
     */
    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @Parameter(description = "用户名") @RequestParam("username") @NonNull String username,
                           @Parameter(description = "密码") @RequestParam("password") @NonNull String password) {

        User user = userService.login(username, password);

        if (user == null) {
            log.warn("登录失败，user 为 null");
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }

        // 登录成功，把 User 对象放到 Session 中
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION, user);

        return AppResult.success();
    }


    /**
     * Created by hanzishuai on 2025/4/8
     *
     * @param request
     * @param id
     * @return com.example.forum.common.AppResult<com.example.forum.model.User>
     * @Description
     */
    @Operation(summary = "获取用户信息")
    @GetMapping("/getUserInfo")
    public AppResult<User> getUserInfo(HttpServletRequest request,
                                       @Parameter(description = "用户 ID") @RequestParam(value = "id", required = false) Long id) {
        User user = null;
        // 根据 id 的值判断 User 对象的获取方式
        if (id == null) {
            // 如果 id 为空，从 Session 中获取当前登录用户的信息
            HttpSession session = request.getSession(false);
            // 从 Session 中获取当前登录用户的信息
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        } else {
            // 如果 id 不为空，从数据库中查询用户信息
            user = userService.selectById(id);
        }

        //  校验
        if (user == null) {
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        return AppResult.success(user);
    }


    @Operation(summary = "退出登录")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request) {
        // 获取 Session 对象
        HttpSession session = request.getSession(false);
        // 判断 Session 是否有效
        if (session != null) {
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            log.info("用户 {} 退出登录", user.getUsername());
            // 销毁 Session
            session.invalidate();
        }

        return AppResult.success("退出成功！");
    }


    /**
     * Created by hanzishuai on 2025/4/12
     *
     * @param username 用户名
     * @param nickname 昵称
     * @param gender   性别
     * @param email    邮箱地址
     * @param phoneNum 手机号
     * @param remark   个人简介
     * @return com.example.forum.common.AppResult
     * @Description 修改个人基本信息
     */
    @Operation(summary = "修改个人基本信息", description = "修改个人基本信息，包含用户名、昵称、性别、邮箱、电话号码、个人简介")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @Parameter(description = "用户名") @RequestParam(value = "name", required = false) String username,
                                @Parameter(description = "昵称") @RequestParam(value = "nickname", required = false) String nickname,
                                @Parameter(description = "性别") @RequestParam(value = "gender", required = false) Byte gender,
                                @Parameter(description = "邮箱地址") @RequestParam(value = "email", required = false) String email,
                                @Parameter(description = "手机号") @RequestParam(value = "phoneNum", required = false) String phoneNum,
                                @Parameter(description = "个人简介") @RequestParam(value = "remark", required = false) String remark) {


        // 校验
        if (!StringUtils.hasLength(username) && !StringUtils.hasLength(nickname)
                && !StringUtils.hasLength(email) && !StringUtils.hasLength(phoneNum)
                && !StringUtils.hasLength(remark) && gender == null) {
            return AppResult.failed("请输入要修改的内容");
        }


        // 从 Session 中获取 user 对象
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 封装对象
        User updateUser = new User();
        updateUser.setId(user.getId()); // 用户 Id
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);

        // 调用 Service
        userService.modifyInfo(updateUser);

        // 查询最新的用户信息
        user = userService.selectById(user.getId());

        // 把新的用户信息设置到 Session 中
        session.setAttribute(AppConfig.USER_SESSION, user);

        // 返回结果
        return AppResult.success(user);
    }


    @Operation(summary = "修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @Parameter(description = "原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @Parameter(description = "新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                    @Parameter(description = "确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {

        // 校验新密码和确认密码是否相等
        if (!newPassword.equalsIgnoreCase(passwordRepeat)) {
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        // 获取当前登录用户的信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 校验用户
        if (user == null || user.getDeleteState() == UserStatus.IS_DELETE.getCode()) {
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        // 调用 Service
        userService.modifyPassword(user.getId(), newPassword, oldPassword);

        // 让 Session 失效
        session.invalidate();


        // 返回结果
        return AppResult.success();
    }

}













